package mementoGeneric;
import java.lang.reflect.*;
import java.util.*;
public class Memento <T>{
	private T tip;
	private Field[] field;
	private ArrayList values;
	public Memento(T tip)
	{
		this.tip=tip;
		try
		{
		this.field=this.tip.getClass().getDeclaredFields();//se obtin toate atributele clasei care reprezinta starea clasei
		values=new ArrayList();
		loadValues();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	public Memento(T t,ArrayList a)
	{
		this.tip=t;
		this.values=a;
	}
	private void loadValues()
	{
		for(int i=0;i<field.length;i++)
		{
			try
			{
			values.add(field[i].get(tip));
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}
	private ArrayList getState()
	{
		return this.values;
		}
	public Memento getMemento()
	{
		return new Memento(tip,values);
	}
	public void restoreMemento(Memento m)
	{
	  ArrayList a=m.getState();
	  for(int i=0;i<a.size();i++)
	  {
		  try{
		  this.field[i].set(tip,a.get(i));
		  }
		  catch(Exception e)
		  {
			  e.printStackTrace();
		  }
	  }
	}


}
